package com.fei.myback.common;

import com.alibaba.fastjson.JSON;
import com.fei.myback.utils.ResoultType;
import com.fei.myback.utils.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 无权限访问
 */
@Component
@Slf4j
public class NullRole implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType(ResultEnum.resoultContentType);
        log.info(request.getMethod());
        log.info(request.getHeader("origin"));
        response.setHeader("Access-Control-Allow-Origin",
                request.getHeader("origin"));
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
        response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        String method = request.getMethod();
        if (method.equals("OPTIONS")) {
            response.setStatus(200);
            return;
        }
        response.getWriter().write(JSON.toJSONString(ResoultType.result(ResultEnum.USER_NO_ACCESS, false)));
    }
}
